import { login, exports, admin, user } from "../../api";
import { returnCompareTime } from "@/libs/util.js";
import Vue from 'vue'
import moment from "moment";
// import { storage } from '../../libs'
const MUTATION_TYPES = {
  TOKEN: "TOKEN",
  USER: "USER",
  MENU: "MENU",
  BATCH: "BATCH",
  EXPORT: "EXPORT",
  SYSTEMBILLDATE: "SYSTEMBILLDATE",
  ISLOGIN: "ISLOGIN",
  UNREADNOTICE: "UNREADNOTICE"
};

const state = {
  userInfo: {},
  menuList: [],
  // 公司别名
  tenantAlias: "",
  // 租户id
  tenantId: null,
  //  userType 1 =>管理员  3=>普通用户
  userType: null,
  // userId  用户id
  userId: null,
  batchNum: null,
  exportNum: null,
  isLogin: null,
  unReadNotice: []
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.BATCH] (state, data) {
    state.batchNum = data.records.length;
  },
  [MUTATION_TYPES.EXPORT] (state, data) {
    state.exportNum = data ? data : null;
  },
  [MUTATION_TYPES.SYSTEMBILLDATE] (state, data) {
    state.systemBillDateInfo = data ? data : null;
  },
  [MUTATION_TYPES.TOKEN] (state, data) {
    sessionStorage.setItem("token", data.access_token);
    state.userId = data.userId;
    // state.tenantId = data.tenantId;
  },
  [MUTATION_TYPES.USER] (state, userInfo = {}) {
    state.userInfo = userInfo;
    sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
    // state.tenantId = userInfo?.tenantId;
    // state.userType = userInfo?.type;
    // state.tenantAlias = userInfo?.tenantAlias;
    // state.tenantName = userInfo?.tenantName;
  },
  [MUTATION_TYPES.MENU] (state, menuList) {
    state.menuList = menuList;
  },
  [MUTATION_TYPES.ISLOGIN] (state, data) {
    state.isLogin = data;
  },
  [MUTATION_TYPES.UNREADNOTICE] (state, data) {
    state.unReadNotice = data || [];
  }
};

const actions = {
  // async login ({ commit }, { username, password }) {
  async login ({ commit, dispatch }, { username, password, mobile, code }) {
    let data = {
      userAccount: username,
      userPassword: password,
      userMobile: mobile,
      userCode: code
    };
    let response = await login.login(data);
    if (response.status !== 200) return;
    commit(MUTATION_TYPES.TOKEN, response.data);

    let userInfo = await login.getUserInfo();
    console.log("用户信息", userInfo);
    if (userInfo.code === 0) {
      commit(MUTATION_TYPES.USER, userInfo.data);
    }

    let menuInfo = await login.getMenuTree();
    console.log("菜单信息", menuInfo);
    if (!menuInfo?.data || menuInfo?.data?.length === 0) {
      Vue.prototype.$message.error('用户没有系统权限，登录失败');
      return
    }

    if (menuInfo.code === 0) {
      commit(MUTATION_TYPES.MENU, menuInfo.data);
    }
    await dispatch('exportCount')
    await dispatch('getSystemBillDate')
    await dispatch('getNotificationList')
    await dispatch('changeLoginFlag', { data: true })
    return { code: 0 };
  },
  async exportCount ({ commit }) {
    let exportInfo = await exports.searchCount();
    if (exportInfo.code === 0) {
      commit(MUTATION_TYPES.EXPORT, exportInfo.data || null);
    }
  },
  async getSystemBillDate ({ commit }) {
    let { code, data } = await admin.getSystemBillDate();
    if (code === 0) {
      if (data?.billDate) {
        let billDateFlag = returnCompareTime(
          new Date(moment(new Date()).format("YYYY-MM-DD HH:mm:ss")),
          new Date(moment(data.billDate).format("YYYY-MM-DD 23:59:59"))
        );
        // 得到关账期的前一月
        let month, year = null;
        if (data.billDate.substring(5, 7) === '01') {
          year = Number(data.billDate.substring(0, 5)) - 1;
          month = 12;
        } else {
          year = data.billDate.substring(0, 5);
          month = Number(data.billDate.substring(5, 7)) - 1 < 10 ? `0${Number(data.billDate.substring(5, 7)) - 1}` : Number(data.billDate.substring(5, 7)) - 1;
        }
        // 关账期前一月的第一天
        let lastMonthDay = year + month + '-' + "01";
        // 关账期当月的第一天
        let sameMonthDay = data.billDate.substring(0, 5) + data.billDate.substring(5, 7) + '-' + "01";
        commit(MUTATION_TYPES.SYSTEMBILLDATE, { billDateFlag, lastMonthDay, sameMonthDay });
      }
    }
  },
  async getNotificationList ({ commit }) {
    let { code, data } = await user.getNotificationList();
    if (code === 0) {
      if (data) {
        commit(MUTATION_TYPES.UNREADNOTICE, data);
      }
    }
  },
  async changeLoginFlag ({ commit }, { data }) {
    commit(MUTATION_TYPES.ISLOGIN, data);
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
